package com.rupertjones.globalcron.domain.scheduling;

import com.rupertjones.globalcron.domain.JobDescriptor;
import com.rupertjones.globalcron.domain.JobExecutionLog;
import com.rupertjones.globalcron.domain.dao.JobDescriptorDAO;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>&copy Rupert Jones 2011,2012</p>
 *
 * @author rup
 */
@Component
@Transactional
public class RecordingExecutionListener implements JobExecutionListener {
    private static final Logger LOG = Logger.getLogger(RecordingExecutionListener.class);

    @Autowired
    private JobDescriptorDAO jobDescriptorDAO;

    @Override
    public void afterExecution(ExecutionContext context) {
        LOG.debug("Recording execution details..");
        JobDescriptor fresh = jobDescriptorDAO.findById(context.getJobDescriptor().getId());
        JobExecutionLog jobExecutionLog = new JobExecutionLog();
        jobExecutionLog.setTimeTaken(context.getTimeTaken());
        jobExecutionLog.setJob(fresh);
        jobExecutionLog.setExecutedNormally(context.getExecutedNormally());
        jobExecutionLog.setSummary(context.getSummary());
        fresh.updateLastFire(context.getLastFire());
        fresh.updateNextFire(context.getNextFire());
        fresh.addOutput(jobExecutionLog);
        if (context.getJobDescriptor().isSaveOutput()) {
            jobExecutionLog.setOutput(context.getOutput());
        }
    }
}
